package com.acme.superchat.service.server;

import com.acme.superchat.service.command.*;

import java.io.*;
import java.net.Socket;
import java.util.List;

/**
 * @author Gregory Sobko
 */
public class ChatWorker implements Runnable {
    private SharedServer server;
    private Socket socket;
    private ClientOutputBuffer clientOutputBuffer;
    private BufferedReader reader;
    private CommandRepository commandRepository;
    private String name="";

    public ChatWorker(Socket socket, SharedServer server) throws IOException {

        InputStream inputStream = socket.getInputStream();
        OutputStream outputStream = socket.getOutputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(outputStream), true);

        this.server = server;
        this.socket = socket;
        reader = bufferedReader;
        commandRepository = new CommandRepository(new ServerConnector(server, this));
        commandRepository.registerCommand(new SndCommand());
        commandRepository.registerCommand(new HistCommand());
        commandRepository.registerCommand(new ChidCommand());
        commandRepository.registerCommand(new ChroomCommand());

        this.server = server;
        clientOutputBuffer = new ClientOutputBuffer(printWriter);
        Thread outputThread = new Thread(clientOutputBuffer);
        outputThread.start();


    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public void run() {
        try {
            String request;
            while ((request=reader.readLine())!=null) {
                commandRepository.parseAndExecuteCommand(request);
            }
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } finally {
            try {
                if (socket != null) {
                    socket.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void sendMessage(String message) {
        clientOutputBuffer.print(message);
    }

    public void sendList(List<String> stringList) {
        clientOutputBuffer.printList(stringList);
    }

}
